<template>
   <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">数据列表    </span>
      
      <el-select style="margin-left: 50px" v-model="subjectId" placeholder="请选择学科"   size="mini">
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
         </el-select>
     
         <el-button
       
        @click="searchType()"
        size="mini">
        查询
      </el-button>
    </el-form>
      <el-button
        class="btn-add"
        @click="showAddDialog()"
        size="mini">
        添加
      </el-button>
    </el-card>
    <el-dialog>
    </el-dialog>
    <div class="table-container">
      <el-table ref="productCateTable"
                style="width: 100%"
                :data="typeOptions"
                 border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column label="题型名称" align="center">
          <template slot-scope="scope">{{scope.row.label}}</template>
        </el-table-column>
       
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="showUpdateDialog(scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="添加题型" :visible.sync="addFormVisible" :close-on-click-modal='false'>
   
	  <el-form :model="addForm" ref="addFormRef" :rules="addFormRule">
	    <el-form-item label="添加题型名称" label-width="`120px`" prop="name">
	      <el-input v-model="addForm.name" autocomplete="off"></el-input>
	    </el-form-item>

	   
	    		
	    <el-form-item prop="checkedSubjectIds">
	    <el-checkbox :indeterminate="addForm.isIndeterminate" v-model="addForm.checkAll" @change="addFormHandleCheckAllChange">全选</el-checkbox>
		  
		  <el-checkbox-group v-model="addForm.checkedSubjectIds"  @change="addFormHandleCheckedSubjectIdsChange">
		  		
			    <el-checkbox v-for="item in subjectOptions" :label="item.value" :key="item.value"> {{item.label}} </el-checkbox>
         		
		  </el-checkbox-group>
		 </el-form-item>

	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="addFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleAdd(addForm.name,addForm.checkedSubjectIds)">确 定</el-button>
	  </div>
  </el-dialog>
    <el-dialog title="修改题型" :visible.sync="updateFormVisible" :close-on-click-modal='false'>
	  <el-form :model="updateForm" ref="updateFormRef" :rules="updateFormRule">
	    <el-form-item label="修改题型名称" label-width="`120px`" prop="name">
	      <el-input v-model="updateForm.name" autocomplete="off"></el-input>
	    </el-form-item>

	     <el-form-item prop="checkedSubjectIds">
	    <el-checkbox :indeterminate="updateForm.isIndeterminate" v-model="updateForm.checkAll" @change="updateFormHandleCheckAllChange">全选</el-checkbox>
		  
		  <el-checkbox-group v-model="updateForm.checkedSubjectIds"  @change="updateFormHandleCheckedSubjectIdsChange">
		  		
			    <el-checkbox v-for="item in subjectOptions" :label="item.value" :key="item.value"> {{item.label}} </el-checkbox>
         		
		  </el-checkbox-group>
		 </el-form-item>
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="updateFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleUpdate(updateForm.id,updateForm.name,updateForm.checkedSubjectIds)">确 定</el-button>
	  </div>
  </el-dialog>
  </div>
</template>
<script type="text/javascript">
	import {mapGetters} from 'vuex'
	import store from '@/store'
	import {fetchSubjectList,fetchList as fetchTypeList,add as addType,deletes as deleteType,update as updateType} from '@/api/type'

	export default {
	    name: "typeList",
	    data() {
	      return {

	      

	      	subjectId: null, //当前学科
	        list: null,
	        //添加学科对话框相应的数据
	        typeOptions:[], //该学科下对应的type选项
	        addFormVisible:false,
	        addForm:{
	        	name:null,
	        	checkedSubjectIds: [],
	        	checkAll:true,
	        	isIndeterminate: false,
	        },
	        addFormRule :{
	          name: [{required: true, message: '请输入题型名称', trigger: 'blur'}],
	          checkedSubjectIds: [{type: 'array', required: true, message: '请选择对应的学科', trigger: 'change'}],

	        },

	        
	        //修改学科对话框相应的数据
	        updateFormVisible:false,
	        updateForm:{
	        	id:null,
	        	name:null,
	        	checkedSubjectIds: [],
	        	checkAll:true,
	        	isIndeterminate: false,
	        },
	        updateFormRule :{
	          name: [{required: true, message: '请输入题型名称', trigger: 'blur'}],
	          checkedSubjectIds: [{type: 'array', required: true, message: '请选择对应的学科', trigger: 'change'}],
	          
	        },
	        
	       

	      }
	    },
	    computed:{
	    	...mapGetters([
	          'subjectOptions',
	          
	        ]),

	    	subjectValueOptions(){
	    		   let arr = []
					this.subjectOptions.forEach(e => {
					   arr.push(e.value)
					})

				return 	arr	
	    	},
	     



	    },
	    created:function(){ 
	    
	    	this.addForm.checkedSubjectIds=this.subjectValueOptions
	    	if((this.subjectOptions===null) || (this.subjectOptions.length===0))
	    		 return
	    	this.subjectId=this.subjectOptions[0].value
	    	
	    },
	    methods:{
	    	addFormHandleCheckAllChange(val) {
		      this.addForm.checkedSubjectIds = val ? this.subjectValueOptions : [];
        	  this.addForm.isIndeterminate = false;
	      	},
	      	addFormHandleCheckedSubjectIdsChange(value) {
		        let checkedCount = value.length;
		        this.addForm.checkAll = checkedCount === this.subjectValueOptions.length;
		        this.addForm.isIndeterminate = checkedCount > 0 && checkedCount < this.subjectValueOptions.length;
	      	},
	      	updateFormHandleCheckAllChange(val) {
		      this.updateForm.checkedSubjectIds = val ? this.subjectValueOptions : [];
        	  this.updateForm.isIndeterminate = false;
	      	},
	      	updateFormHandleCheckedSubjectIdsChange(value) {
		        let checkedCount = value.length;
		        this.updateForm.checkAll = checkedCount === this.subjectValueOptions.length;
		        this.updateForm.isIndeterminate = checkedCount > 0 && checkedCount < this.subjectValueOptions.length;
	      	},

	    	searchType(){

	    		fetchTypeList({"subjectId":this.subjectId}).then(response => {
		          this.typeOptions = [];
		          let allTypeList = response.data.list;
		          if (allTypeList===null) return
		          for (let i = 0; i < allTypeList.length; i++) {
		            this.typeOptions.push({label: allTypeList[i].name, value: allTypeList[i].id});
		          }
		         
		        }).catch(error=>{
		          this.$message({
				            type: 'error',
				              message: error,
				              duration:1000
				     });
		        });


	    	},
	    	

	    	showAddDialog(){
	    		this.addForm.name=''
	    		this.addFormVisible=true
	    	},
	    	handleAdd(name,checkedSubjectIds) {
	    		this.$refs.addFormRef.validate(valid => {
	    			if (valid) {
	    				
			    		addType({"name":name,"subjectIds":checkedSubjectIds.join(",")}).then(response=>{
			    			
			    			this.$store.dispatch('GetTypeListAll')
				    		this.addFormVisible=false
				    		this.$message({
				                type: 'success',
				                message: '添加成功',
				                duration:1000
				             });
				    		this.searchType()

			    		}).catch(error=>{
			    			 this.addFormVisible=false
			    			 this.$message({
				                type: 'error',
				                message: '添加失败',
				                duration:1000
				             });
			    		})
			    	}
        		})
		    },

		    showUpdateDialog(row){
	    		this.updateForm.name=row.label
	    		this.updateForm.id=row.value
	    		this.updateFormVisible=true
	    		let that=this
	    		fetchSubjectList({"id":this.updateForm.id}).then(response=>{
		        	that.updateForm.checkedSubjectIds = [];
		        	
		        	that.updateForm.checkedSubjectIds = response.data.list;		
		        })

	    	},
	    	handleUpdate(id,name,checkedSubjectIds) {
        		this.$refs.updateFormRef.validate(valid => {
	    			if (valid) {
		        		updateType({"id":id,"name":name,"subjectIds":checkedSubjectIds.join(",")}).then(response=>{
		        			
				    		this.$store.dispatch('GetTypeListAll')
				    		this.updateFormVisible=false
					    	this.$message({
						                type: 'success',
						                message: '更新成功',
						                duration:1000
						             });
			    			this.searchType()

			    		}).catch(error=>{
			    			this.updateFormVisible=false
					    			 this.$message({
						                type: 'error',
						                message: '更新失败',
						                duration:1000
						             });
			    			})
			    	}
			    })
		    },

		    handleDelete( row) {
		        this.$confirm('是否要删除该题型？如果删除，将彻底删除所有相关的试题！', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	 this.$confirm('再次确认删除该题型？', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(() => {
				        	deleteType({"id":row.value}).then(response=>{
					    		this.$store.dispatch('GetTypeListAll')
					    		this.$message({
						                type: 'success',
						                message: '删除成功',
						                duration:1000
						             });
					    		this.searchType()

					    	}).catch(() => {
		          				this.$message({
					                type: 'error',
					                message: '删除失败',
					                duration:1000
					            });
		          
		       				});


				        }).catch(() => {
		          				
		          
		       			 });
		          
		        }).catch(() => {
		          	
		          
		        });
		      }
	    }
	    
	}
	
	
</script>